/**
 * This is MainActivity.
 * @author fufeng
 * @Time 2023-6-22
 */

package com.example.myapplication.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.db.Data;
import com.example.myapplication.db.SQLiteManager;
import com.example.myapplication.fragment.MainFragment;
import com.example.myapplication.fragment.PlaneFragment;
import com.example.myapplication.login.LoginActivity;
import com.example.myapplication.services.MQTTService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends AppCompatActivity
                        implements MainFragment.MainFragmentListener {
    private MainFragment mainFragment;//显示传感器节点列表的Fragment
    private Spinner spinner;//显示龙芯节点的下拉栏控件
    private Button switchView;
    private boolean switchViewFlag = false;
    private TextView textView;
    private Button refresh;//刷新传感器节点列表的Button控件
    private Button login;//用于登录的Button控件
    private SimpleDateFormat df = new SimpleDateFormat(Data.DATE_FORMAT_Y);//设置日期格式
    public static Handler handler;//处理MQTT服务器返回消息的handler
    private String username = null;//MQTT客户端ID
    private String clientID = null;//MQTT客户端ID
    private String passWord = null;//MQTT客户端密钥
    private String gatewayID;
    private static List<String> LoongSonItem = new ArrayList<String>();//存储龙芯节点名的容器
    private boolean saveFlag;//登录界面返回的是否保存密码的标志位
    private MQTTService mqttService;
    private SQLiteManager dataHelper;//SQLite
    private SQLiteDatabase db;//SQLite
    private HashMap<String, String> Sites = new HashMap<String, String>();
    ActivityResultLauncher<Intent> DataActivityLauncher;//用于启动数据显示Activity
    ActivityResultLauncher<Intent> CarControlActivityLauncher;//用于启动数据显示Activity
    ActivityResultLauncher<Intent> intentActivityResultLauncher;//用于启动登录Activity

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.tv);

        login = (Button)findViewById(R.id.login);
        /**
         * 设置Button点击事件为启动登录
         * */
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                intentActivityResultLauncher.launch(intent);
            }
        });
        switchView = (Button)findViewById(R.id.switchView);
        switchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!switchViewFlag){
                    Bundle bundle = new Bundle();
                    //bundle.putString(Data.COLUMN_Gateway, View.get);
                    bundle.putString(Data.COLUMN_Gateway, gatewayID);
                    bundle.putString(Data.COLUMN_GatewayType, Sites.get(gatewayID));
                    PlaneFragment planeFragment = PlaneFragment.newInstance(bundle);
                    getFragmentManager().beginTransaction().replace(R.id.linearLayout, planeFragment,
                            "planeFragment").commitAllowingStateLoss();
                    switchViewFlag = !switchViewFlag;
                }else {
                    List<String> oldItem = new ArrayList<String>();
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                            android.R.layout.simple_list_item_1, LoongSonItem);
                    spinner.setAdapter(adapter);
                    switchViewFlag = !switchViewFlag;
                }

            }
        });
        refresh = (Button)findViewById(R.id.refresh);
        /**
         * 设置Button点击事件为刷新Spinner
         * */
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> oldItem = new ArrayList<String>();
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_list_item_1, LoongSonItem);
                spinner.setAdapter(adapter);
            }
        });
        spinner = (Spinner)findViewById(R.id.spinner);
        /**
         * 设置Spinner点击事件为刷新mainFragment为当前选定的龙芯节点下的传感器节点
         * */
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                gatewayID = parent.getItemAtPosition(position).toString();
                //Toast.makeText(MainActivity.this, gatewayID, Toast.LENGTH_SHORT).show();
                Bundle bundle = new Bundle();
                bundle.putString(Data.COLUMN_Gateway, gatewayID);
                bundle.putString(Data.COLUMN_GatewayType, Sites.get(gatewayID));
                mainFragment = MainFragment.newInstance(bundle);
                getFragmentManager().beginTransaction().replace(R.id.linearLayout, mainFragment,
                        "mainFragment").commitAllowingStateLoss();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        LoongSonItem.clear();

        dataHelper = new SQLiteManager(this);
        db = dataHelper.getWritableDatabase();
        /**
         * 删除所有缓存的节点信息，等待最新的节点信息
         * */
        db.delete(Data.SensorData_Table, null, null);
        db.delete(Data.NodeLocal_Table, null, null);
        db.delete(Data.NodeArray_Table, null, null);
        db.close();

        /**
         * 初始化DataActivityLauncher
         * */
        DataActivityLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {

                    }
                });

        CarControlActivityLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {

                    }
                });
        /**
         * 初始化intentActivityResultLauncher，并处理返回数据
         * */
        intentActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK){
                    username = result.getData().getStringExtra(Data.COLUMN_Username);
                    clientID = result.getData().getStringExtra(Data.COLUMN_ClientID);
                    passWord = result.getData().getStringExtra(Data.COLUMN_Password);
                    saveFlag = result.getData().getBooleanExtra(Data.COLUMN_SaveFlag, false);
                }
            }
        });
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intentActivityResultLauncher.launch(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        /**
         * 因为每次Resume都需要重新连接MQTT服务器，并请求数据，所以需要删除之前的节点信息，不然就会有重复
         * */
        LoongSonItem.clear();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, LoongSonItem);
        spinner.setAdapter(adapter);

        if((clientID != null && clientID.length() != 0) && (passWord != null && passWord.length() != 0)){
            Intent intent=new Intent(MainActivity.this,MQTTService.class);
            Bundle bundle = new Bundle();
            bundle.putString(Data.COLUMN_Username, username);
            bundle.putString(Data.COLUMN_ClientID, clientID);
            bundle.putString(Data.COLUMN_Password, passWord);
            bundle.putBoolean(Data.COLUMN_SaveFlag, saveFlag);
            intent.putExtras(bundle);
            startService(intent);
        }


        /**
         * 处理MQTT返回数据的handler
         * */
        handler = new Handler() {

            @SuppressLint({"SetTextIl8n", "HandlerLeak"})

            public void handleMessage(Message msg) {

                super.handleMessage(msg);

                switch (msg.what) {

                    case 1: //开机校验更新回传

                        break;

                    case 2: //反馈回转

                        break;

                    case 3: //MQTT收到消息
                        String message = msg.getData().getString(Data.MQTTReceiveMessage);
                        String topic = (String) msg.obj;
                        try {
                            if(topic.indexOf(Data.TopicLoongSonSync) != -1) {
                                String[] str = message.split("_");
                                //收到同步的龙芯ID号，将其加入到下拉栏里
                                if (!LoongSonItem.contains(message)) {
                                    LoongSonItem.add(str[0]);
                                    Sites.put(str[0], str[1]);
                                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                                            android.R.layout.simple_list_item_1, LoongSonItem);
                                    spinner.setAdapter(adapter);
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        break;

                    default:

                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    /**
     * 用于mainFragment打开数据显示Activity
     * */
    @Override
    public void OpenDataActivity(Bundle bundle) {
        Intent intent = new Intent(MainActivity.this, DataActivity.class);

        Toast.makeText(this, "OpenDataActivity", Toast.LENGTH_SHORT).show();

        bundle.putString(Data.COLUMN_ClientID, clientID);
        bundle.putString(Data.COLUMN_Password, passWord);
        intent.putExtras(bundle);
        DataActivityLauncher.launch(intent);
    }

    @Override
    public void OpenCarControlActivity(Bundle bundle) {
        Intent intent = new Intent(MainActivity.this, CarControlActivity.class);
        intent.putExtras(bundle);
        CarControlActivityLauncher.launch(intent);
    }
}